package com.odin.core.controller;

import com.odin.core.dao.RoleMapper;
import com.odin.core.dao.UserMapper;
import com.odin.core.dao.UserRoleMapper;
import com.odin.core.entity.User;
import com.odin.core.entity.UserRole;
import com.odin.core.service.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapperl;
    @Autowired
    UserRoleMapper userRoleMapper;
    @RequiresPermissions("user:get")
    @RequestMapping("/get")
    @ResponseBody
    public User findUserByLoginName(String loginName){
      return   userService.findUserByLoginName(loginName);
    }

    @RequestMapping("list")
    public String list(Model model){
        model.addAttribute("list",userMapper.findAll());
        return "user/list";
    }

    @RequestMapping("editUserRole")
    public String editUserRole(String userId,Model model){
        model.addAttribute("userId",userId);
        model.addAttribute("list",roleMapperl.findAll());
        return "user/editRole";
    }

    @RequestMapping("saveUserRole")
    public String saveUserRole(String userId, Model model, HttpServletRequest request){
        String[] roles = request.getParameterValues("roles");
        System.out.print(roles);
        //先删除所有角色
        userRoleMapper.deleteByUser(userId);
        if(roles!=null && roles.length!=0){
            for (String role:roles) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(role);
                userRole.setUserId(userId);
                userRoleMapper.insert(userRole);
            }
        }
        return "redirect:list";
    }
    @RequestMapping("save")
    public String save(User user,Model model){
        User userByLoginName = userMapper.findUserByLoginName(user.getLoginName());
        if(userByLoginName!=null){
            model.addAttribute("msg","登录名已经存在");
            return "user/userAdd";
        }
        String salt = UUID.randomUUID().toString();
        user.setId(salt);
        //密码加密
        String result = new SimpleHash("MD5",user.getPassword(),salt,2).toString();
        user.setPassword(result);
        userMapper.insert(user);
        return "redirect:list";
    }

    @RequestMapping("toAdd")
    public String toAdd(){
        return "user/userAdd";
    }

}
